package com.liu.webstore.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @Author LiuYumei
 * @Date 2022/7/19 11:01 AM
 */
public class VerifyCodeUtil {
    public static String drewRandomText(int width, int height, BufferedImage image) {
        Graphics2D g = (Graphics2D) image.getGraphics();
        g.setColor(Color.yellow);
        g.setFont(new Font("微软雅黑", Font.BOLD, 40));
        String baseNumLetter = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder builder = new StringBuilder();
        int x = 10;
        String ch;
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            g.setColor(getRandomColor());
            int degree = random.nextInt() % 30;
            int dot = random.nextInt(baseNumLetter.length());
            random.nextInt(baseNumLetter.length());
            ch = baseNumLetter.charAt(dot) + "";
            builder.append(ch);

            //正向旋转
            g.rotate(degree * Math.PI / 180, x, 45);
            g.drawString(ch, x, 45);

            //反向旋转
            g.rotate(-degree * Math.PI / 180, x, 45);
            x += 48;
        }
        for (int i = 0; i < 6; i++) {
            // 设置随机颜色
            g.setColor(getRandomColor());

            // 随机画线
            g.drawLine(random.nextInt(width), random.nextInt(height),
                    random.nextInt(width), random.nextInt(height));
        }

        //添加噪点
        for (int i = 0; i < 30; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            g.setColor(getRandomColor());
            g.fillRect(x1, y1, 2, 2);
        }
        return builder.toString();
    }

    private static Color getRandomColor() {
        Random random = new Random();
        return new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    }
}
